package ActiveMQ.selecter;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by brossdong on 2017/12/16.
 */
public class Receiver {

    public final String SELECTOR_1 = "color = 'blue'";
    public final String SELECTOR_2 = "color = 'blue' AND sal > 2000";

    //连接工厂
    private ConnectionFactory connectionFactory;

    //连接对象
    private Connection connection;

    //session对象
    private Session session;

    //消费者
    private MessageConsumer messageConsumer;

    //目标地址
    Destination destination;

    public Receiver() {
        try {
            this.connectionFactory = new ActiveMQConnectionFactory(
                    ActiveMQConnectionFactory.DEFAULT_USER,
                    ActiveMQConnectionFactory.DEFAULT_PASSWORD,
                    "tcp://localhost:61616");
            this.connection = this.connectionFactory.createConnection();
            this.connection.start();
            this.session = this.connection.createSession(Boolean.FALSE,Session.AUTO_ACKNOWLEDGE);
            this.destination = this.session.createQueue("first");

            this.messageConsumer = this.session.createConsumer(this.destination,SELECTOR_1);
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }

    public  void receiver() {
        try{
            this.messageConsumer.setMessageListener(new Listener());
        }catch (JMSException e) {
            e.printStackTrace();
        }
    }
    class Listener implements MessageListener{
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {

                }

                if (message instanceof MapMessage) {
                    MapMessage ret = (MapMessage) message;
                    System.out.println(ret.toString());
                    System.out.println(ret.getString("name"));
                    System.out.println(ret.getString("age"));
                }
            }catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        receiver.receiver();
    }

}
